var mongoose = require('mongoose');
var EventProxy = require('eventproxy');
var config = require('../config');
var moment = require('moment');
var _ = require('lodash');

var models = require('../models');
var Tab = models.Tab;
var Topic = models.Topic;
var User = models.User;
var Reply = models.Reply;

var services = require('../services');
var userServ = services.user;
var topicServ = services.topic;
var replyServ = services.reply;


exports.index = function (req, res, next) {
	var tid = req.params.tid;
	var page = parseInt(req.params.page) || 1;
	var ep = new EventProxy();
	ep.fail(next);	//500
	
	ep.all('topic', 'replies', 'pageTotal', function (topic, replies, pageTotal) {
		//主题浏览数
		topic.views++;
		topic.save(ep.done(function () {
			res.locals.tabs = config.tabs;
			res.render('topic', { topic: topic, replies: replies, pageTotal: pageTotal, page: page });
		}));
	});
	//获取主题
	topicServ.getFullTopicById(tid, ep.done(function (msg, topic) {
		if (msg) return res.render404(msg);
		ep.emit('topic', topic);
	}));

	var options = {
		skip: config.replyPageLimit * (page - 1),
		limit: config.replyPageLimit,
		sort: '+createAt'
	};
	//获取回复
	replyServ.queryList({ topicId: tid }, options, ep.done(function (msg, replies) {
		if (msg) return res.render404(msg);
		ep.emit('replies', replies);
	}));
	//获取回复页数
	replyServ.queryPage({ topicId: tid }, ep.done('pageTotal'));
}

exports.create = function (req, res, next) {
	var tabId = req.body.tabId,
		title = req.body.title,
		tags = req.body.tags,
		content = req.body.content;
	// console.log(tabId);
	// console.log(title);
	// console.log(tags);
	// console.log(content);
	var ep = new EventProxy();
	ep.fail(next);
	ep.on('create_error', function (msg) {
		res.json({ result: 'fail', msg: msg });
	});
	if (!title || !content) {
		return ep.emit('create_error', '信息不能为空！');
	}
	if (!req.session.user) {
		return ep.emit('create_error', '没有权限！');
	}
	Tab.findById(tabId, ep.done(function (tab) {
		if (!tab) return ep.emit('create_error', '板块不存在！');
		var topic = new Topic();
		topic.title = title;
		topic.content = content;
		topic.tabId = tabId;
		_.uniq(tags.trim().split(/,|;|\s/)).forEach(function (tag) {
			if (tag) topic.tags.push(tag);
		});

		topic.authorId = req.session.user._id;
		topic.save(ep.done(function () {
			res.json({ result: 'success' });
		}));
	}));
}